<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\service\EnvConfigService;

/**
 * 环境配置控制器
 */
class EnvConfig extends Backend
{
    protected array $noNeedLogin = ['info'];
    protected array $noNeedPermission = ['info'];

    /**
     * 获取环境配置信息
     */
    public function info(): void
    {
        // 只有超级管理员可以查看环境信息
        // if (!$this->auth->isSuperAdmin()) {
        //     $this->error('无权限查看环境配置信息');
        // }

        $info = EnvConfigService::getEnvironmentInfo();
        
        // 隐藏敏感信息
        if (isset($info['database']['password'])) {
            $info['database']['password'] = '******';
        }
        if (isset($info['redis']['password'])) {
            $info['redis']['password'] = '******';
        }

        $this->success('', [
            // 'environment_info' => $info,
            'environment_status' => [
                'is_production' => EnvConfigService::isProduction(),
                'is_test' => EnvConfigService::isTest(),
                'is_local' => EnvConfigService::isLocal(),
            ]
        ]);
    }

    /**
     * 获取当前环境
     */
    public function getCurrentEnvironment(): void
    {
        $this->success('', [
            'environment' => EnvConfigService::getCurrentEnvironment(),
            'is_production' => EnvConfigService::isProduction(),
            'is_test' => EnvConfigService::isTest(),
            'is_local' => EnvConfigService::isLocal(),
        ]);
    }

    /**
     * 获取环境配置值
     */
    public function getConfig(): void
    {
        $key = $this->request->param('key');
        if (empty($key)) {
            $this->error('配置键不能为空');
        }

        // 检查是否为敏感配置
        $sensitiveKeys = ['password', 'secret', 'key', 'token'];
        $isSensitive = false;
        foreach ($sensitiveKeys as $sensitiveKey) {
            if (strpos(strtolower($key), $sensitiveKey) !== false) {
                $isSensitive = true;
                break;
            }
        }

        $value = EnvConfigService::get($key);
        
        if ($isSensitive && !empty($value)) {
            $value = '******';
        }

        $this->success('', [
            'key' => $key,
            'value' => $value,
            'is_sensitive' => $isSensitive
        ]);
    }
} 